package com.decent.ejfadmin.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;

/**
 * describe:
 *
 * @author JunLei He
 * @date 2018年06月30日
 */
@Slf4j
public class MyBatisRedisCache implements Cache {
    private static RedisTemplate<Object, Object> redisTemplate;
    private Long clearInterval;
    private String id;

    public MyBatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        try {
            CacheNamespace annotation = Class.forName(id).getAnnotation(CacheNamespace.class);
            clearInterval = annotation.flushInterval();
        } catch (Exception e) {
            log.error("MyBatisRedisCache error{}", e.getMessage(), e);
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        try {
            if (Objects.isNull(value) || Objects.isNull(key)) {
                return;
            }
            redisTemplate.opsForValue().set(key, value, clearInterval, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("MyBatisRedisCache->缓存放入异常[{}]{}", key, e, e);
        }
    }

    @Override
    public Object getObject(Object key) {
        Object result = null;
        try {
            result = redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("getObject error[{}]", key, e, e);
        }
        return result;
    }

    @Override
    public Object removeObject(Object key) {
        try {
            redisTemplate.delete(key.toString());
        } catch (Exception e) {
            log.error("MyBatisRedisCache->缓存信息删除[{}] {}", key, e, e);
        }
        return null;
    }

    @Override
    public void clear() {

    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }

    public static void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        MyBatisRedisCache.redisTemplate = redisTemplate;
    }
}
